<template>
  <div id="app">
    <div class="test-tree">
      <div class="test-tree__search">
        <input v-model="keyword" type="text" /><button @click="handleSearchClick">搜索</button>
      </div>
      <div class="test-tree__result">
        <virtual-tree 
          height="300px"
          ref="tree"
          :current="320700"
          :data="treeData" 
          :default-expand-level="1" 
          label-key="name"
          :filter-method="handleFilterMethod"
          :default-expand-keys="[110101]"
        >
          <span slot="addon" slot-scope="{ node }">
            {{node.data.name}}
          </span>
        </virtual-tree> 
      </div>
    </div>
  </div>
</template>

<script>
import VirtualTree from '@/index.js'
import treeData from './tree-data.json'

export default {
  name: 'App',
  components: {
    VirtualTree
  },
  data () {
    return {
      keyword: '',
      current: ''
    }
  },
  computed: {
    data () {
      return treeData
    },
    treeData () {
      if (!this.data) {
        return []
      }
      const data = JSON.parse(JSON.stringify(this.data))
      const keys = Object.keys(data)
      return (keys || []).reduce((rs, k) => {
        const item = this.data[k]
        if (item && item.level === 1) {
          if (item.children) {
            item.children = item.children.map(v => this.data[v])
            item.children.forEach(vv => {
              if (vv.children) {
                vv.children = vv.children.map(vvv => this.data[vvv])
                vv.children.forEach(vvv => {
                  delete vvv.children
                })
              }
              if (vv.children && !vv.children.length) {
                delete vv.children
              }
            })
            if (!item.children.length) {
              delete item.children
            }
          }
          rs.push(item)
        }
        return rs
      }, [])
    }
  },
  methods: {
    handleSearchClick () {
      this.$refs.tree.filter(this.keyword)
    },
    handleFilterMethod ({ node, keyword }) {
      if (!keyword) {
        return true
      }
      return node.data.name.indexOf(keyword) >= 0
    }
  }
}
</script>

<style>
.test-tree{
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 480px;
  margin: 30px auto;
}
.test-tree__search{
  padding: 6px;
  text-align: center;
  border-bottom: 1px solid #ddd;;
}
</style>
